package com.tulele.vtool.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tulele.vtool.mapper.BTeamInfoMapper;
import com.tulele.vtool.mapper.BTeamRelationMapper;
import com.tulele.vtool.mapper.UserInfoMapper;
import com.tulele.vtool.model.BTeamRelation;
import com.tulele.vtool.model.UserInfo;
import com.tulele.vtool.model.combinedEntity.BTeamDayNumber;
import com.tulele.vtool.model.combinedEntity.BTeamInfoUser;
import com.tulele.vtool.model.combinedEntity.BTeamRelationArticle;
import com.tulele.vtool.service.BTeamRelationService;
import com.tulele.vtool.utils.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 团队关系信息表(BTeamRelation)表服务实现类
 *
 * @author makejava
 * @since 2020-09-09 16:09:59
 */
@Service("bTeamRelationService")
public class BTeamRelationServiceImpl implements BTeamRelationService {
    /**
     * 服务对象
     */
    @Resource
    private BTeamRelationMapper bTeamRelationMapper;

    /**
     * 服务对象
     */
    @Resource
    private BTeamInfoMapper bTeamInfoMapper;

    /**
     * 服务对象
     */
//    @Value("${spring.profiles.active}")
//    private String springProfilesActive;

    /**
     * 服务对象
     */
    @Resource
    private UserInfoMapper userInfoMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public BTeamRelation queryById(Integer id) {
        return this.bTeamRelationMapper.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<BTeamRelation> queryAllByLimit(int offset, int limit) {
        return this.bTeamRelationMapper.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param bTeamRelation 实例对象
     * @return 实例对象
     */
    @Override
    public BTeamRelation insert(BTeamRelation bTeamRelation) {
        this.bTeamRelationMapper.insert(bTeamRelation);
        return bTeamRelation;
    }

    /**
     * 修改数据
     *
     * @param bTeamRelation 实例对象
     * @return 实例对象
     */
    @Override
    public BTeamRelation update(BTeamRelation bTeamRelation) {
        this.bTeamRelationMapper.update(bTeamRelation);
        return this.queryById(bTeamRelation.getId());
    }

    /**
     * 批量修改数据
     *
     * @param bTeamRelation 实例对象
     * @return 实例对象
     */
    @Override
    public void updatebTeamRelation(BTeamRelation bTeamRelation, String springProfilesActive) {
        BTeamRelation bTeamRelationDto = new BTeamRelation();

        bTeamRelationDto.setGzhCode(springProfilesActive);//公众号标识
        bTeamRelationDto.setTeamId(bTeamRelation.getTeamId());

        List<BTeamRelation> bTeamRelationList = this.queryAll(bTeamRelationDto);

        if (bTeamRelationList.size() > 0) {
            for (int i = 0; i < bTeamRelationList.size(); i++) {
                BTeamRelation bTeamRelationListOne = bTeamRelationList.get(i);

                bTeamRelationListOne.setTeamName(bTeamRelation.getTeamName());

                this.bTeamRelationMapper.update(bTeamRelationListOne);
            }
        }
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.bTeamRelationMapper.deleteById(id) > 0;
    }

    /**
     * 通过主键设置管理员
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean setManageById(Integer id){
        return this.bTeamRelationMapper.setManageById(id) > 0;
    }

    /**
     * 通过实体作为筛选条件查询
     *
     * @param bTeamRelation 实例对象
     * @return 对象列表
     */
    @Override
    public List<BTeamRelation> queryAll(BTeamRelation bTeamRelation) {
        return this.bTeamRelationMapper.queryAll(bTeamRelation);
    }

    /**
     * 通过userId查询自己的团队
     *
     * @param
     * @return 多条数据
     */
    @Override
    public List<BTeamRelation> queryMyBTeamInfoByUserId(BTeamRelation bTeamRelation, String springProfilesActive) {
        BTeamRelation bTeamRelationDto = new BTeamRelation();

        bTeamRelationDto.setUserId(bTeamRelation.getUserId());//创建人userId
        bTeamRelationDto.setGzhCode(springProfilesActive);//公众号标识
        bTeamRelationDto.setUserFlag(1);//展示状态（0停用 1正常）

        List<BTeamRelation> bTeamRelationService = this.bTeamRelationMapper.queryMyBTeamInfoByUserId(bTeamRelationDto);

        return bTeamRelationService;
    }

    /**
     * 通过userId查询自己当前团队
     *
     * @param
     * @return 多条数据
     */
    @Override
    public BTeamRelation queryBTeamInfoByUserId(BTeamRelation bTeamRelation, String springProfilesActive) {
        BTeamRelation bTeamRelationDto = new BTeamRelation();

        bTeamRelationDto.setUserId(bTeamRelation.getUserId());//创建人userId
        bTeamRelationDto.setGzhCode(springProfilesActive);//公众号标识
        bTeamRelationDto.setUserFlag(1);//展示状态（0停用 1正常）
        bTeamRelationDto.setUserTeamNow(1);//当前所属团队 0-离开 1-正在

        BTeamRelation bTeamRelationService = this.bTeamRelationMapper.queryBTeamInfoByUserId(bTeamRelationDto);

        return bTeamRelationService;
    }

    /**
     * 查询当前团队成员
     *
     * @param
     * @return 多条数据
     */
    @Override
    public List<BTeamInfoUser> selectBTeamRelationByTeamId(BTeamRelation bTeamRelation, String springProfilesActive) {
        BTeamRelation bTeamRelationDto = new BTeamRelation();

        bTeamRelationDto.setTeamId(bTeamRelation.getTeamId());//团队id
        bTeamRelationDto.setGzhCode(springProfilesActive);//公众号标识
        bTeamRelationDto.setUserFlag(1);//展示状态（0停用 1正常）

        List<BTeamRelation> bTeamRelationList = this.bTeamRelationMapper.queryAll(bTeamRelationDto);

        List<BTeamInfoUser> bTeamInfoUser = new ArrayList<>();
        for (int i = 0; i < bTeamRelationList.size(); i++) {
            BTeamInfoUser bTeamInfoUserOne = new BTeamInfoUser();
            BTeamRelation getElement = bTeamRelationList.get(i);

            UserInfo userInfo = this.userInfoMapper.queryUserMainInfo(getElement.getUserId());
            if (userInfo != null) {

                Integer shareCount = this.bTeamRelationMapper.queryShareCount(getElement.getUserId());

                Integer lookCount = this.bTeamRelationMapper.queryLookCount(getElement.getUserId());

                bTeamInfoUserOne.setUserId(getElement.getUserId());

                bTeamInfoUserOne.setNickName(Optional.ofNullable(userInfo.getNickName()).orElse(""));
                bTeamInfoUserOne.setAvatarUrl(Optional.ofNullable(userInfo.getAvatarUrl()).orElse(""));

                bTeamInfoUserOne.setTeamRole(getElement.getTeamRole());

                bTeamInfoUserOne.setShareCount(shareCount);
                bTeamInfoUserOne.setLookCount(lookCount);
                if (shareCount == null) {
                    bTeamInfoUserOne.setShareCount(0);
                }

                if (lookCount == null) {
                    bTeamInfoUserOne.setLookCount(0);
                }

                bTeamInfoUser.add(bTeamInfoUserOne);
            }
        }

        return bTeamInfoUser
                .stream()
                .sorted(Comparator.comparing(BTeamInfoUser::getLookCount, Comparator.nullsFirst(Integer::compareTo)).reversed())
                .collect(Collectors.toList());
    }

    /**
     * 查询当前团队成员
     *
     * @param
     * @return 多条数据
     */
    @Override
    public List<BTeamInfoUser> selectBTeamRelationByTeamIdAndDay(BTeamRelation bTeamRelation, BTeamDayNumber bTeamDayNumber, String springProfilesActive) {
        BTeamRelation bTeamRelationDto = new BTeamRelation();

        bTeamRelationDto.setTeamId(bTeamRelation.getTeamId());//团队id
        bTeamRelationDto.setGzhCode(springProfilesActive);//公众号标识
        bTeamRelationDto.setUserFlag(1);//展示状态（0停用 1正常）

        Integer dayNumber = bTeamDayNumber.getDayNumber();

        List<BTeamRelation> bTeamRelationList = this.bTeamRelationMapper.queryAll(bTeamRelationDto);

        List<BTeamInfoUser> bTeamInfoUser = new ArrayList<>();
        for (int i = 0; i < bTeamRelationList.size(); i++) {
            BTeamInfoUser bTeamInfoUserOne = new BTeamInfoUser();
            BTeamRelation getElement = bTeamRelationList.get(i);

            UserInfo userInfo = this.userInfoMapper.queryUserMainInfo(getElement.getUserId());

            Integer shareCount = this.bTeamRelationMapper.queryShareCountByDayNumber(getElement.getUserId(), dayNumber);

            Integer lookCount = this.bTeamRelationMapper.queryLookCountByDayNumber(getElement.getUserId(), dayNumber);

            bTeamInfoUserOne.setUserId(getElement.getUserId());
            bTeamInfoUserOne.setNickName(userInfo.getNickName());
            bTeamInfoUserOne.setAvatarUrl(userInfo.getAvatarUrl());
            bTeamInfoUserOne.setTeamRole(getElement.getTeamRole());

            bTeamInfoUserOne.setShareCount(shareCount);
            bTeamInfoUserOne.setLookCount(lookCount);
            if (shareCount == null) {
                bTeamInfoUserOne.setShareCount(0);
            }

            if (lookCount == null) {
                bTeamInfoUserOne.setLookCount(0);
            }

            bTeamInfoUser.add(bTeamInfoUserOne);
        }

        return bTeamInfoUser
                .stream()
                .sorted(Comparator.comparing(BTeamInfoUser::getLookCount, Comparator.nullsFirst(Integer::compareTo)).reversed())
                .collect(Collectors.toList());
    }

    /**
     * 通过团队ID查询当前队长可以移除的团队成员
     *
     * @param
     * @return 多条数据
     */
    @Override
    public List<BTeamInfoUser> selectRemoveBTeamRelationByTeamId(BTeamRelation bTeamRelation, String springProfilesActive) {
        BTeamRelation bTeamRelationDto = new BTeamRelation();

        bTeamRelationDto.setTeamId(bTeamRelation.getTeamId());//团队id
        bTeamRelationDto.setGzhCode(springProfilesActive);//公众号标识
        bTeamRelationDto.setUserFlag(1);//展示状态（0停用 1正常）
        bTeamRelationDto.setTeamRole(0);//成员角色 0-团队普通成员 1-团队管理员 2-团队队长

        List<BTeamRelation> bTeamRelationList = this.bTeamRelationMapper.queryAll(bTeamRelationDto);

        //把管理员的也查出来 20210721 hyl
        bTeamRelationDto.setTeamRole(1);//成员角色 0-团队普通成员 1-团队管理员 2-团队队长
        bTeamRelationList.addAll(this.bTeamRelationMapper.queryAll(bTeamRelationDto));

        List<BTeamInfoUser> bTeamInfoUser = new ArrayList<>();
        for (int i = 0; i < bTeamRelationList.size(); i++) {
            BTeamInfoUser bTeamInfoUserOne = new BTeamInfoUser();
            BTeamRelation getElement = bTeamRelationList.get(i);

            UserInfo userInfo = this.userInfoMapper.queryUserMainInfo(getElement.getUserId());

            if(userInfo!=null) {
                bTeamInfoUserOne.setUserId(userInfo.getUserId());
                bTeamInfoUserOne.setNickName(userInfo.getNickName());
                bTeamInfoUserOne.setAvatarUrl(userInfo.getAvatarUrl());
                bTeamInfoUserOne.setTeamRole(getElement.getTeamRole());

                bTeamInfoUser.add(bTeamInfoUserOne);
            }
        }
        return bTeamInfoUser;
    }

    /**
     * 查询是否已经在团队里面
     *
     * @param
     * @return 一条团队成员数据
     */
    @Override
    public BTeamRelation selectOnBTeamRelation(BTeamRelation bTeamRelation, String springProfilesActive) {
        BTeamRelation bTeamRelationDto = new BTeamRelation();

        //是否正在当前团队
        bTeamRelationDto.setTeamId(bTeamRelation.getTeamId());//团队ID
        bTeamRelationDto.setUserId(bTeamRelation.getUserId());//成员userId
        bTeamRelationDto.setGzhCode(springProfilesActive);//公众号标识
        bTeamRelationDto.setUserFlag(1);//展示状态（0停用 1正常）

        return this.bTeamRelationMapper.queryOne(bTeamRelationDto);
    }

    /**
     * 加入团队
     *
     * @param
     * @return 一条团队成员数据
     */
    @Override
    public BTeamRelation inviterBTeamRelation(BTeamRelation bTeamRelation, String springProfilesActive) {
        BTeamRelation bTeamRelationDto = new BTeamRelation();

        bTeamRelationDto.setUserId(bTeamRelation.getUserId());//成员userId
        bTeamRelationDto.setGzhCode(springProfilesActive);//公众号标识
        bTeamRelationDto.setUserTeamNow(1);//当前所属团队 0-离开 1-正在

        List<BTeamRelation> bTeamRelationList = this.bTeamRelationMapper.queryAll(bTeamRelationDto);

        //如果有团队先离开
        if (CollectionUtils.isNotEmpty(bTeamRelationList)) {
            for (int i = 0; i < bTeamRelationList.size(); i++) {
                BTeamRelation bTeamRelationOne = new BTeamRelation();
                BTeamRelation upset = bTeamRelationList.get(i);

                bTeamRelationOne.setId(upset.getId());
                bTeamRelationOne.setUserTeamNow(0);//当前所属团队 0-离开 1-正在
                this.bTeamRelationMapper.update(bTeamRelationOne);
            }
        }

        bTeamRelationDto.setTeamId(bTeamRelation.getTeamId());//团队ID
        bTeamRelationDto.setTeamName(bTeamRelation.getTeamName());//团队名称
        bTeamRelationDto.setUserId(bTeamRelation.getUserId());//成员userId
        bTeamRelationDto.setGzhCode(springProfilesActive);//公众号标识
        bTeamRelationDto.setUserTeamNow(1);//当前所属团队 0-离开 1-正在
        bTeamRelationDto.setInviterId(bTeamRelation.getInviterId());//邀请人userId
        bTeamRelationDto.setTeamRole(0);//成员角色 0-团队普通成员 1-团队管理员 2-团队队长
        bTeamRelationDto.setUserFlag(1);//展示状态（0停用 1正常）
        bTeamRelationDto.setCreateTime(DateUtil.getCurDate());//创建时间
        bTeamRelationDto.setUpdateTime(DateUtil.getCurDate());//更新时间
        bTeamRelationDto.setTeamRemark("");//备注

        this.bTeamRelationMapper.insert(bTeamRelationDto);

        return bTeamRelationDto;
    }

    /**
     * 退出团队
     *
     * @param
     * @return 一条团队成员数据
     */
    @Override
    public BTeamRelation quitBTeamRelation(BTeamRelation bTeamRelation) {

        BTeamRelation bTeamRelationDto = new BTeamRelation();
        return bTeamRelationDto;
    }

    /**
     * 队长批量移除团队成员
     *
     * @param
     * @return 多条团队成员数据
     */
    @Override
    public BTeamRelation removeBTeamRelation(List<BTeamRelation> bTeamRelation) {
        for (int i = 0; i < bTeamRelation.size(); i++) {
            BTeamRelation upset = bTeamRelation.get(i);

            //找到被移除团队成员userId
            this.bTeamRelationMapper.queryUserIdById(upset.getId());

            //移除团队成员
            this.bTeamRelationMapper.deleteById(upset.getId());
        }
        return null;
    }

    /**
     * 切换当前所处团队
     *
     * @param
     * @return
     */
    @Override
    public int cutBTeamInfo(BTeamRelation bTeamRelation, String springProfilesActive) {
        BTeamRelation bTeamRelationDto = new BTeamRelation();

        bTeamRelationDto.setUserId(bTeamRelation.getUserId());//成员userId
        bTeamRelationDto.setGzhCode(springProfilesActive);//公众号标识
        bTeamRelationDto.setUserTeamNow(1);//当前所属团队 0-离开 1-正在
        bTeamRelationDto.setUserFlag(1);//展示状态（0停用 1正常）

        List<BTeamRelation> bTeamRelationList = this.bTeamRelationMapper.queryAll(bTeamRelationDto);

        //如果有团队先离开
        if (CollectionUtils.isNotEmpty(bTeamRelationList)) {
            for (int i = 0; i < bTeamRelationList.size(); i++) {
                BTeamRelation bTeamRelationUp = new BTeamRelation();
                BTeamRelation upset = bTeamRelationList.get(i);

                bTeamRelationUp.setId(upset.getId());
                bTeamRelationUp.setUserTeamNow(0);//当前所属团队 0-离开 1-正在
                this.bTeamRelationMapper.update(bTeamRelationUp);
            }
        }

        bTeamRelationDto.setTeamId(bTeamRelation.getTeamId());//团队ID
        bTeamRelationDto.setUserTeamNow(0);//当前所属团队 0-离开 1-正在
        bTeamRelationDto.setId(this.bTeamRelationMapper.queryOne(bTeamRelationDto).getId());//团队关系ID
        bTeamRelationDto.setUserTeamNow(1);//当前所属团队 0-离开 1-正在
        this.bTeamRelationMapper.update(bTeamRelationDto);

        return bTeamRelationDto.getId();
    }

    /**
     * 退出团队后，切换到某个团队
     *
     * @param
     * @return 一条团队成员数据
     */
    @Override
    public String addLastBTeamRelation(BTeamRelation bTeamRelation, String springProfilesActive) {
        BTeamRelation bTeamRelationDto = new BTeamRelation();

        bTeamRelationDto.setUserId(bTeamRelation.getUserId());//成员userId
        bTeamRelationDto.setGzhCode(springProfilesActive);//公众号标识
        bTeamRelationDto.setUserTeamNow(1);//当前所属团队 0-离开 1-正在
        bTeamRelationDto.setUserFlag(1);//展示状态（0停用 1正常）

        BTeamRelation bTeamRelationService1 = this.bTeamRelationMapper.queryLastBTeam(bTeamRelationDto);

        if (bTeamRelationService1 == null) {
            bTeamRelationDto.setUserTeamNow(0);//当前所属团队 0-离开 1-正在
            BTeamRelation bTeamRelationService0 = this.bTeamRelationMapper.queryLastBTeam(bTeamRelationDto);

            if (bTeamRelationService0 == null) {
                return "没有团队~";
            }

            bTeamRelationService0.setUserTeamNow(1);
            this.bTeamRelationMapper.update(bTeamRelationService0);

            return "切换到" + bTeamRelationService0.getTeamName();
        }
        return "没有切换团队~";
    }

    /**
     * 查询当前团队成员文章
     *
     * @param
     * @return
     */
    @Override
    public List<BTeamRelationArticle> selectBTeamArticle(BTeamRelation bTeamRelation, String springProfilesActive) {
        BTeamRelation bTeamRelationDto = new BTeamRelation();

        bTeamRelationDto.setUserId(bTeamRelation.getUserId());//用户userId
        bTeamRelationDto.setGzhCode(springProfilesActive);//公众号标识
        bTeamRelationDto.setUserTeamNow(1);//当前所属团队 0-离开 1-正在
        bTeamRelationDto.setUserFlag(1);//展示状态（0停用 1正常）

        List<BTeamRelationArticle> bTeamRelationArticle = this.bTeamRelationMapper.selectBTeamArticle(bTeamRelationDto);

        return bTeamRelationArticle;
    }

    @Override
    public PageInfo<BTeamRelationArticle> selectBTeamArticles(Integer pageNum, Integer pageSize, BTeamRelation bTeamRelation, String springProfilesActive) {

        BTeamRelation bTeamRelationDto = new BTeamRelation();

        bTeamRelationDto.setUserId(bTeamRelation.getUserId());//用户userId
        bTeamRelationDto.setGzhCode(springProfilesActive);//公众号标识
        bTeamRelationDto.setUserTeamNow(1);//当前所属团队 0-离开 1-正在
        bTeamRelationDto.setUserFlag(1);//展示状态（0停用 1正常）

        Integer teamId = this.bTeamRelationMapper.selectBTeamArticleTeamId(bTeamRelationDto);
        bTeamRelationDto.setUserId(null);//用户userId
        bTeamRelationDto.setTeamId(teamId);//团队ID

        PageHelper.startPage(pageNum, pageSize);
        List<BTeamRelationArticle> bTeamRelationArticles = this.bTeamRelationMapper.selectBTeamArticle(bTeamRelationDto);

        return new PageInfo<BTeamRelationArticle>(bTeamRelationArticles);
    }
}
